package com.tyc.utill;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedissonLock implements ILock{

    private final RedissonClient redissonClient;
    private final String LOCK_NAME = "LOCK";

    public RedissonLock(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        RLock lock = redissonClient.getLock(LOCK_NAME);
        // 1 获取锁的最大等待时间，10 锁过期时间
        try {
            return  lock.tryLock(1, 10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void unlock() {
        RLock lock = redissonClient.getLock(LOCK_NAME);
        lock.unlock();
    }
}
